import { GameConfig } from '../config/GameConfig.js';
import { svgAssetManager } from './SVGAssetManager.js';

export class RenderSystem {
    private ctx: CanvasRenderingContext2D;
    private svgCache: Map<string, HTMLImageElement> = new Map();

    constructor(ctx: CanvasRenderingContext2D) {
        this.ctx = ctx;
    }

    async init(): Promise<void> {
        console.log('🎨 初始化渲染系统...');
        // 设置默认渲染状态
        this.ctx.imageSmoothingEnabled = true;
        this.ctx.imageSmoothingQuality = 'high';
        
        // 预加载SVG资源
        await this.preloadSVGAssets();
        
        console.log('✅ 渲染系统初始化完成');
    }

    private async preloadSVGAssets(): Promise<void> {
        try {
            const essentialAssets = [
                'FATEH_110', 'SHAHAB_3', 'FATTAH_2', 'SHAHED_136', 'QIAM_1', 'ZELZAL_2',
                'IRON_DOME', 'ARROW_3', 'GREEN_PINE_RADAR',
                'EXPLOSION'
            ];
            
            console.log('🔄 开始预加载SVG资源...');
            await svgAssetManager.preloadAssets(essentialAssets);
            console.log('✅ SVG资源预加载完成');
        } catch (error) {
            console.warn('⚠️ SVG资源预加载失败，将使用备用方案:', error);
        }
    }

    clear(): void {
        this.ctx.clearRect(0, 0, GameConfig.CANVAS_WIDTH, GameConfig.CANVAS_HEIGHT);
    }

    renderBackground(): void {
        // 渲染伊朗发射区域
        this.renderIranArea();
        
        // 渲染地中海区域
        this.renderSeaArea();
        
        // 渲染特拉维夫防御区域
        this.renderDefenseArea();
        
        // 渲染防御网格
        this.renderDefenseGrid();
    }

    private renderIranArea(): void {
        this.ctx.save();
        
        // 背景渐变
        const gradient = this.ctx.createLinearGradient(0, 0, GameConfig.IRAN_AREA_WIDTH, 0);
        gradient.addColorStop(0, GameConfig.COLORS.IRAN_PRIMARY);
        gradient.addColorStop(1, GameConfig.COLORS.IRAN_SECONDARY);
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, GameConfig.IRAN_AREA_WIDTH, GameConfig.CANVAS_HEIGHT);
        
        // 边界线
        this.ctx.strokeStyle = GameConfig.COLORS.IRAN_ACCENT;
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 5]);
        this.ctx.beginPath();
        this.ctx.moveTo(GameConfig.IRAN_AREA_WIDTH, 0);
        this.ctx.lineTo(GameConfig.IRAN_AREA_WIDTH, GameConfig.CANVAS_HEIGHT);
        this.ctx.stroke();
        
        // 区域标签
        this.ctx.fillStyle = 'white';
        this.ctx.font = 'bold 14px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('伊朗发射区', GameConfig.IRAN_AREA_WIDTH / 2, 20);
        
        this.ctx.restore();
    }

    private renderSeaArea(): void {
        this.ctx.save();
        
        const startX = GameConfig.IRAN_AREA_WIDTH;
        
        // 背景渐变
        const gradient = this.ctx.createLinearGradient(startX, 0, startX + GameConfig.SEA_AREA_WIDTH, 0);
        gradient.addColorStop(0, GameConfig.COLORS.MEDITERRANEAN);
        gradient.addColorStop(0.5, '#4682B4');
        gradient.addColorStop(1, GameConfig.COLORS.MEDITERRANEAN);
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(startX, 0, GameConfig.SEA_AREA_WIDTH, GameConfig.CANVAS_HEIGHT);
        
        // 波浪效果
        this.renderWaves(startX);
        
        // 区域标签
        this.ctx.fillStyle = 'white';
        this.ctx.font = 'bold 14px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
        this.ctx.lineWidth = 2;
        this.ctx.strokeText('地中海飞行区域', startX + GameConfig.SEA_AREA_WIDTH / 2, 20);
        this.ctx.fillText('地中海飞行区域', startX + GameConfig.SEA_AREA_WIDTH / 2, 20);
        
        this.ctx.restore();
    }

    private renderWaves(startX: number): void {
        this.ctx.save();
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
        this.ctx.lineWidth = 1;
        
        const waveHeight = 10;
        const waveLength = 50;
        const numWaves = Math.ceil(GameConfig.SEA_AREA_WIDTH / waveLength);
        
        for (let i = 0; i < 3; i++) {
            const y = GameConfig.CANVAS_HEIGHT - 100 + i * 30;
            this.ctx.beginPath();
            
            for (let j = 0; j <= numWaves; j++) {
                const x = startX + j * waveLength;
                const waveY = y + Math.sin((j * 0.5) + (Date.now() * 0.001)) * waveHeight;
                
                if (j === 0) {
                    this.ctx.moveTo(x, waveY);
                } else {
                    this.ctx.lineTo(x, waveY);
                }
            }
            this.ctx.stroke();
        }
        
        this.ctx.restore();
    }

    private renderDefenseArea(): void {
        this.ctx.save();
        
        const startX = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
        
        // 背景渐变
        const gradient = this.ctx.createLinearGradient(startX, 0, startX + GameConfig.DEFENSE_AREA_WIDTH, 0);
        gradient.addColorStop(0, GameConfig.COLORS.URBAN_GRAY);
        gradient.addColorStop(1, '#556B2F');
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(startX, 0, GameConfig.DEFENSE_AREA_WIDTH, GameConfig.CANVAS_HEIGHT);
        
        // 边界线
        this.ctx.strokeStyle = GameConfig.COLORS.ISRAEL_PRIMARY;
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 5]);
        this.ctx.beginPath();
        this.ctx.moveTo(startX, 0);
        this.ctx.lineTo(startX, GameConfig.CANVAS_HEIGHT);
        this.ctx.stroke();
        
        // 城市轮廓
        this.renderCitySkyline(startX);
        
        // 区域标签
        this.ctx.fillStyle = 'white';
        this.ctx.font = 'bold 14px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
        this.ctx.lineWidth = 2;
        this.ctx.strokeText('特拉维夫防御区', startX + GameConfig.DEFENSE_AREA_WIDTH / 2, 20);
        this.ctx.fillText('特拉维夫防御区', startX + GameConfig.DEFENSE_AREA_WIDTH / 2, 20);
        
        this.ctx.restore();
    }

    private renderCitySkyline(startX: number): void {
        this.ctx.save();
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
        
        // 简单的城市轮廓
        const buildings = [
            { x: 50, width: 30, height: 80 },
            { x: 90, width: 25, height: 120 },
            { x: 130, width: 40, height: 60 },
            { x: 180, width: 35, height: 100 },
            { x: 230, width: 20, height: 140 },
            { x: 260, width: 45, height: 70 },
            { x: 310, width: 30, height: 90 }
        ];
        
        buildings.forEach(building => {
            const x = startX + building.x;
            const y = GameConfig.CANVAS_HEIGHT - building.height - 50;
            this.ctx.fillRect(x, y, building.width, building.height);
            
            // 窗户
            this.ctx.fillStyle = 'rgba(255, 255, 0, 0.3)';
            for (let row = 0; row < Math.floor(building.height / 15); row++) {
                for (let col = 0; col < Math.floor(building.width / 8); col++) {
                    if (Math.random() > 0.7) {
                        const windowX = x + col * 8 + 2;
                        const windowY = y + row * 15 + 2;
                        this.ctx.fillRect(windowX, windowY, 4, 6);
                    }
                }
            }
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
        });
        
        this.ctx.restore();
    }

    private renderDefenseGrid(): void {
        this.ctx.save();
        
        const startX = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
        const gridSize = GameConfig.DEFENSE_GRID_SIZE;
        
        this.ctx.strokeStyle = 'rgba(46, 134, 171, 0.3)';
        this.ctx.lineWidth = 1;
        this.ctx.setLineDash([]);
        
        // 绘制网格线
        for (let row = 0; row <= GameConfig.DEFENSE_GRID_ROWS; row++) {
            const y = row * gridSize;
            this.ctx.beginPath();
            this.ctx.moveTo(startX, y);
            this.ctx.lineTo(startX + GameConfig.DEFENSE_AREA_WIDTH, y);
            this.ctx.stroke();
        }
        
        for (let col = 0; col <= GameConfig.DEFENSE_GRID_COLS; col++) {
            const x = startX + col * gridSize;
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, GameConfig.DEFENSE_GRID_ROWS * gridSize);
            this.ctx.stroke();
        }
        
        this.ctx.restore();
    }

    // 渲染实体的通用方法
    renderEntity(x: number, y: number, width: number, height: number, color: string): void {
        this.ctx.save();
        this.ctx.fillStyle = color;
        this.ctx.fillRect(x - width / 2, y - height / 2, width, height);
        this.ctx.restore();
    }

    // 渲染圆形实体
    renderCircleEntity(x: number, y: number, radius: number, color: string): void {
        // 🔍 临时调试：记录所有圆形渲染调用
        if (radius > 10) { // 只记录大圆形（拦截器）
            console.log(`🎨 渲染大圆形: (${x.toFixed(1)}, ${y.toFixed(1)}) r=${radius} color=${color}`);
        }
        
        this.ctx.save();
        this.ctx.fillStyle = color;
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, Math.PI * 2);
        this.ctx.fill();
        this.ctx.restore();
    }

    // 渲染文本
    renderText(text: string, x: number, y: number, color: string = 'white', font: string = '12px Arial'): void {
        this.ctx.save();
        this.ctx.fillStyle = color;
        this.ctx.font = font;
        this.ctx.fillText(text, x, y);
        this.ctx.restore();
    }

    // 渲染线条
    renderLine(x1: number, y1: number, x2: number, y2: number, color: string = 'white', width: number = 1): void {
        this.ctx.save();
        this.ctx.strokeStyle = color;
        this.ctx.lineWidth = width;
        this.ctx.beginPath();
        this.ctx.moveTo(x1, y1);
        this.ctx.lineTo(x2, y2);
        this.ctx.stroke();
        this.ctx.restore();
    }

    // 渲染爆炸效果
    renderExplosion(x: number, y: number, radius: number, intensity: number = 1): void {
        this.ctx.save();
        
        const gradient = this.ctx.createRadialGradient(x, y, 0, x, y, radius);
        gradient.addColorStop(0, `rgba(255, 255, 255, ${intensity})`);
        gradient.addColorStop(0.3, `rgba(255, 165, 0, ${intensity * 0.8})`);
        gradient.addColorStop(0.6, `rgba(255, 69, 0, ${intensity * 0.6})`);
        gradient.addColorStop(1, `rgba(139, 0, 0, 0)`);
        
        this.ctx.fillStyle = gradient;
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, Math.PI * 2);
        this.ctx.fill();
        
        this.ctx.restore();
    }

    // SVG渲染方法
    async renderSVG(assetKey: string, x: number, y: number, width: number, height: number, rotation: number = 0): Promise<boolean> {
        try {
            const svgContent = svgAssetManager.getSVG(assetKey);
            if (!svgContent) {
                return false; // SVG不可用，使用备用方案
            }

            this.ctx.save();
            this.ctx.translate(x, y);
            this.ctx.rotate(rotation);
            
            // 简化的SVG渲染：直接使用颜色形状代替复杂的SVG转换
            this.drawSVGPlaceholder(assetKey, -width/2, -height/2, width, height);
            
            this.ctx.restore();
            return true;
        } catch (error) {
            console.warn(`SVG渲染失败: ${assetKey}`, error);
            return false;
        }
    }

    private drawSVGPlaceholder(assetKey: string, x: number, y: number, width: number, height: number): void {
        // 根据资源类型绘制不同的形状和颜色
        this.ctx.fillStyle = this.getSVGColor(assetKey);
        
        if (assetKey.includes('MISSILE') || assetKey.includes('FATEH') || assetKey.includes('SHAHAB') || assetKey.includes('FATTAH') || assetKey.includes('SHAHED') || assetKey.includes('QIAM') || assetKey.includes('ZELZAL')) {
            // 导弹：绘制火箭形状
            this.ctx.fillRect(x, y, width, height);
            this.ctx.fillStyle = 'orange';
            this.ctx.fillRect(x - 2, y + height/2 - 1, 4, 2); // 尾焰
        } else if (assetKey.includes('IRON_DOME') || assetKey.includes('ARROW') || assetKey.includes('RADAR')) {
            // 防御系统：绘制六边形
            this.ctx.beginPath();
            const centerX = x + width/2;
            const centerY = y + height/2;
            const radius = Math.min(width, height) / 2;
            
            for (let i = 0; i < 6; i++) {
                const angle = (i * Math.PI) / 3;
                const pointX = centerX + radius * Math.cos(angle);
                const pointY = centerY + radius * Math.sin(angle);
                if (i === 0) {
                    this.ctx.moveTo(pointX, pointY);
                } else {
                    this.ctx.lineTo(pointX, pointY);
                }
            }
            this.ctx.closePath();
            this.ctx.fill();
        } else {
            // 默认：矩形
            this.ctx.fillRect(x, y, width, height);
        }
    }

    private getSVGColor(assetKey: string): string {
        // 根据资源类型返回合适的颜色
        if (assetKey.includes('FATEH')) return '#CC2B4A';
        if (assetKey.includes('SHAHAB')) return '#8B0000';
        if (assetKey.includes('FATTAH')) return '#FFB627';
        if (assetKey.includes('SHAHED')) return '#7B2D26';
        if (assetKey.includes('QIAM')) return '#A0522D';
        if (assetKey.includes('ZELZAL')) return '#B22222';
        if (assetKey.includes('IRON_DOME')) return '#2E86AB';
        if (assetKey.includes('ARROW')) return '#A23B72';
        if (assetKey.includes('RADAR')) return '#F18F01';
        return '#666666';
    }

    // 带备用方案的导弹渲染
    renderMissileWithSVG(missileType: string, x: number, y: number, width: number, height: number, rotation: number, fallbackColor: string, fallbackIcon: string): boolean {
        // 先尝试SVG渲染
        const svgContent = svgAssetManager.getSVG(missileType);
        if (svgContent) {
            this.ctx.save();
            this.ctx.translate(x, y);
            this.ctx.rotate(rotation);
            this.drawSVGPlaceholder(missileType, -width/2, -height/2, width, height);
            this.ctx.restore();
            return true;
        } else {
            // SVG未加载，返回false让调用者使用备用方案
            return false;
        }
    }

    // 带备用方案的防御系统渲染
    renderDefenseSystemWithSVG(systemType: string, x: number, y: number, size: number, fallbackColor: string, fallbackIcon: string): boolean {
        const svgContent = svgAssetManager.getSVG(systemType);
        if (svgContent) {
            this.ctx.save();
            this.drawSVGPlaceholder(systemType, x - size/2, y - size/2, size, size);
            this.ctx.restore();
            return true;
        } else {
            // SVG未加载，返回false让调用者使用备用方案
            return false;
        }
    }
}
